//
//  JKMainViewController.swift
//  ZhiHuDaily-Swift
//
//  Created by albert on 2018/3/2.
//  Copyright © 2018年 安永博. All rights reserved.
//

import UIKit

class JKMainViewController: UIViewController {
    
    // MARK: - 公共属性
    
    /** 3Dtouch的跳转标识 */
    var jumpTo: String?
    
    
    // MARK: - 私有属性
    
    private var _index: Int = -1
    
    /** 动画时间 */
    private let animationDuration: CGFloat = 0.5
    
    /** 摇一摇夜间模式是否打开 */
    private var isShakeCanChangeSkin = true
    
    /** 当前皮肤模式 */
    private var currentSkinModel: String?
    
    /** drawerScrollView开始拖拽时的x偏移 */
    private var beginDragingOffX: CGFloat = 0
    
    /** 最底层的scrollView */
    private lazy var drawerScrollView: JKDrawerScrollView = {
        
        let drawerScrollView = JKDrawerScrollView(frame: JKScreenBounds)
        
        drawerScrollView.delegate = self
        drawerScrollView.scrollsToTop = false
        drawerScrollView.contentSize = CGSize(width: self.view.width + JKScreenW * 3 / 5, height: self.view.height)
        drawerScrollView.contentOffset = CGPoint(x: JKScreenW * 3 / 5, y: 0)
        drawerScrollView.isPagingEnabled = true
        drawerScrollView.bounces = false
        drawerScrollView.showsHorizontalScrollIndicator = false
        drawerScrollView.showsVerticalScrollIndicator = false
        
        return drawerScrollView
    }()
    
    /** 左侧栏控制器 */
    private lazy var leftVc: JKLeftViewController = {
        
        let leftVc = JKLeftViewController()
        
        self.addChildViewController(leftVc)
        leftVc.view.frame = CGRect(x: 0, y: 0, width: JKScreenW * 3 / 5, height: JKScreenH)
        
        return leftVc
    }()
    
    /** 主导航控制器 */
    private weak var mainNav: JKMainNavigationController?
    
    /** 当前主控制器 */
    private weak var currentVc: UIViewController?
    
    /** 主页控制器 */
    private weak var homeVc: JKHomeViewController?
    
    /** 其它主题控制器 */
    private weak var baseThemeVc: JKBaseThemeViewController?
    
    /** 侧滑后点击隐藏侧栏的按钮 */
    private lazy var coverBtn: UIButton? = {
        
        let coverBtn = UIButton(type: UIButtonType.custom)
        
        coverBtn.backgroundColor = UIColor.clear
        coverBtn.frame = CGRect(x: JKScreenW * 3 / 5, y: 0, width: JKScreenW * 2 / 5, height: JKScreenH)
        coverBtn.addTarget(self, action: #selector(JKMainViewController.coverBtnClick), for: UIControlEvents.touchUpInside)
        self.drawerScrollView.addSubview(coverBtn)
        
        return coverBtn
    }()
    
    // MARK: - 初始化

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.white
        
        setup()
        
        startMonitor()
        
        NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActive), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil)
        
        handle3DTouch()
    }
    
    @objc private func applicationDidBecomeActive() {
        
        handle3DTouch()
    }
    
    @objc private func handle3DTouch() {
        
        if (jumpTo == nil) { return }
        
        if jumpTo == "最新日报" {
            
            JKNewsListGetDataModel.loadLatestData(finishedBlock: { (dict, error) in
                
                if dict == nil || error != nil {
                    
                    return
                }
                
                let model = (dict![JKStoryListModelKey] as! [JKNewsListModel]).first
                
                let detailVc = JKNewsDetailViewController()
                
                detailVc.storyID = model?.id
                detailVc.is3DTouchJump = true
                detailVc.storyListVc = self.homeVc
                
                self.mainNav?.pushViewController(detailVc, animated: true)
                
                self.homeVc?.reload3DTouchReadWithID(storyID: detailVc.storyID)
            })
            
        }else if jumpTo == "最新瞎扯" {
            
            JKNetworkingTool.shared.request(url: "http://news-at.zhihu.com/api/3/section/2", method: .get, parameters: nil) { (responseJson, error) in
                
                if error != nil {
                    
                    return
                }
                
                guard let json = responseJson as? [String : AnyObject] else {
                    
                    return
                }
                
                guard let stories = (json["stories"]) as? [[String : AnyObject]] else {
                    
                    return
                }
                
                guard let newsListModels = [JKNewsListModel].deserialize(from: stories) else {
                    
                    return
                }
                
                let model = newsListModels.first
                
                let detailVc = JKNewsDetailViewController()
                
                detailVc.storyID = model??.id
                detailVc.is3DTouchJump = true
                detailVc.storyListVc = self.homeVc
                
                self.mainNav?.pushViewController(detailVc, animated: true)
                
                self.homeVc?.reload3DTouchReadWithID(storyID: detailVc.storyID)
            }
        }
        
        jumpTo = nil
    }
    
    private func setup() {
        
        view.addSubview(drawerScrollView)
        
        drawerScrollView.addSubview(leftVc.view)
        
        let homeVc = JKHomeViewController()
        let mainNav = JKMainNavigationController(rootViewController: homeVc)
        self.homeVc = homeVc
        currentVc = homeVc
        
        self.addChildViewController(mainNav)
        self.mainNav = mainNav
        
        mainNav.view.frame = JKScreenBounds
        mainNav.view.x = self.leftVc.view.width
        
        weak var weakSelf = self
        
        mainNav.showLeftVcBlock = {
            
            weakSelf?.showLeftVc()
        }
        
        drawerScrollView.insertSubview(mainNav.view, belowSubview: leftVc.view)
        
        UIApplication.shared.setStatusBarStyle(UIStatusBarStyle.lightContent, animated: true)
    }
    
    private func startMonitor() {
        
        weak var weakSelf = self
        
        leftVc.iconBtnBlock = { // 头像
            
            weakSelf?._index = -1
            
            if !JKAccountManager.shared.isLogin {
                
                JKLoginViewController.show()
                
            }else{
                
                if weakSelf?.currentVc is JKMeViewController {
                    
                    weakSelf?.coverBtnClick()
                    
                    return
                }
                
                let meVc = JKMeViewController()
                
                meVc.logoutBlock = {
                    
                    weakSelf?.changeToSetting()
                }
                
                weakSelf?.changeMainNavWithVc(vc: meVc)
            }
        }
        
        leftVc.collectionBtnBlock = { // 收藏
            
            weakSelf?._index = -1
            
            if weakSelf?.currentVc?.isMember(of: JKMyCollectionViewController.self) ?? false  {
                
                weakSelf?.coverBtnClick()
                
                return
            }
            
            let vc = JKMyCollectionViewController()
            
            weakSelf?.changeMainNavWithVc(vc: vc)
        }
        
        leftVc.messageBtnBlock = { // 消息
            
            weakSelf?._index = -1
            
            if weakSelf?.currentVc?.isMember(of: JKMessageViewController.self) ?? false {
                
                weakSelf?.coverBtnClick()
                
                return
            }
            
            let vc = JKMessageViewController()
            
            weakSelf?.changeMainNavWithVc(vc: vc)
        }
        
        leftVc.settingBtnBlock = { // 设置
            
            weakSelf?._index = -1
            
            weakSelf?.changeToSetting()
        }
        
        leftVc.cellSelectedBlock = { (themeModel, index) in
            
            if weakSelf?._index == index {
                
                weakSelf?.coverBtnClick()
                
                return
            }
            
            weakSelf?._index = index
            
            if index == 0 { // 首页
                
                let vc = JKHomeViewController()
                weakSelf?.changeMainNavWithVc(vc: vc)
                weakSelf?.homeVc = vc
                
            }else if index == 1 { // 专栏
                
                let vc = JKSpecialColumnViewController()
                weakSelf?.changeMainNavWithVc(vc: vc)
                
            }else{ // 其它主题
                
                if weakSelf?.baseThemeVc != nil {
                    
                    weakSelf?.baseThemeVc!.themeModel = themeModel
                    weakSelf?.coverBtnClick()
                    weakSelf?.baseThemeVc!.loadNewData()
                    return
                }
                
                let vc = JKBaseThemeViewController()
                vc.themeModel = themeModel
                weakSelf?.changeMainNavWithVc(vc: vc)
                weakSelf?.baseThemeVc = vc
            }
        }
    }
    
    // MARK: - action
    
    /** 切换控制器 */
    private func changeMainNavWithVc(vc: UIViewController) {
        
        currentVc = vc
        
        coverBtn?.isHidden = true
        
        weak var weakSelf = self
        
        let mainNav = JKMainNavigationController(rootViewController: vc)
        
        mainNav.showLeftVcBlock = {
            
            weakSelf?.showLeftVc()
        }
        
        mainNav.view.frame = JKScreenBounds
        mainNav.view.x = JKScreenW * 3 / 5
        weakSelf?.addChildViewController(mainNav)
        weakSelf?.drawerScrollView.insertSubview(mainNav.view, at: 0)
        
        UIView.animate(withDuration: 0.5, animations: {
            
            weakSelf?.mainNav?.view.alpha = 0
            weakSelf?.drawerScrollView.contentOffset = CGPointMake(JKScreenW * 3 / 5, 0)
            
        }) { (_) in
            
            weakSelf?.mainNav?.view.removeFromSuperview()
            weakSelf?.mainNav?.removeFromParentViewController()
            weakSelf?.mainNav = mainNav
        }
    }
    
    /** 切换到设置 */
    private func changeToSetting() {
        
        if self.mainNav?.viewControllers.first is JKSettingViewController {
            
            coverBtnClick()
            
            return
        }
        
        coverBtn?.isHidden = true
        
        weak var weakSelf = self
        
        let mainNav = UIStoryboard(name: "JKSettingViewController", bundle: nil).instantiateInitialViewController() as! JKMainNavigationController
        
        mainNav.showLeftVcBlock = {
            
            weakSelf?.showLeftVc()
        }
        
        mainNav.view.frame = JKScreenBounds
        mainNav.view.x = JKScreenW * 3 / 5
        weakSelf?.addChildViewController(mainNav)
        weakSelf?.drawerScrollView.insertSubview(mainNav.view, at: 0)
        
        UIView.animate(withDuration: 0.5, animations: {
            
            weakSelf?.mainNav?.view.alpha = 0
            weakSelf?.drawerScrollView.contentOffset = CGPointMake(JKScreenW * 3 / 5, 0)
            
        }) { (_) in
            
            weakSelf?.mainNav?.view.removeFromSuperview()
            weakSelf?.mainNav?.removeFromParentViewController()
            weakSelf?.mainNav = mainNav
        }
    }
    
    /** 显示侧栏 */
    private func showLeftVc() {
        
        leftVc.updateUserIconAndName()
        
        UIView.animate(withDuration: TimeInterval(animationDuration), animations: {
            
            self.drawerScrollView.contentOffset = CGPoint.zero
            
        }) { (_) in
            
            self.coverBtn?.isHidden = false
        }
    }
    
    /** 点击隐藏侧栏 */
    @objc private func coverBtnClick() {
        
        UIView.animate(withDuration: TimeInterval(animationDuration), animations: {
            
            self.drawerScrollView.contentOffset = CGPoint(x: JKScreenW * 3 / 5, y: 0)
            
        }) { (_) in
            
            self.coverBtn?.isHidden = true
        }
        
    }
    
    // 摇一摇
    override func motionBegan(_ motion: UIEventSubtype, with event: UIEvent?) {
        super.motionBegan(motion, with: event)
        
        if (motion != UIEventSubtype.motionShake) { return }
        
        isShakeCanChangeSkin = UserDefaults.standard.bool(forKey: JKIsShakeCanChangeSkinKey)
        
        if !isShakeCanChangeSkin { return }
        
        currentSkinModel = UserDefaults.standard.string(forKey: JKCurrentSkinModelKey)
        
        if currentSkinModel == JKNightSkinModelValue { // 当前为夜间模式，切换至日间模式
            
            UserDefaults.standard.set(JKDaySkinModelValue, forKey: JKCurrentSkinModelKey)
            UserDefaults.standard.synchronize()
            
        } else {// 当前为日间模式，切换至夜间模式
            
            UserDefaults.standard.set(JKNightSkinModelValue, forKey: JKCurrentSkinModelKey)
            UserDefaults.standard.synchronize()
            
        }
        
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: JKSkinModelDidChangedNotification), object: self)
    }
    
    deinit {
        
        NotificationCenter.default.removeObserver(self)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

// MARK: - UIScrollViewDelegate

extension JKMainViewController: UIScrollViewDelegate {
    
    func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
        
        controlCoverButton()
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        
        controlCoverButton()
    }
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        
        controlCoverButton()
    }
    
    private func controlCoverButton() {
        
        if (drawerScrollView.contentOffset.x == 0) {
            
            coverBtn?.isHidden = false
            leftVc.updateUserIconAndName()
            
        }else{
            
            coverBtn?.isHidden = true
        }
    }
}
